﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Model;
using BLL;
using System.Data;
using System.Data.SqlClient;
using WebPortal.Models;
using System.Web.Script.Serialization;
using System.Text;
using Common;

namespace WebPortal.Controllers
{
    public class JobTaskController : BaseController
    {
        #region List

        public ActionResult List(string dbName)
        {

            PageRole role = new PageRole();
            role.role = SysPublicBLL.GetUserRole(Request.Cookies["MDM_UserName"].Value, dbName);
            return View(role);
        }

        public ActionResult AllTask()
        {
            return View();
        }

        [HttpPost]
        public ActionResult GetTaskList(string dbName, FormCollection formCollection)
        {
            string taskName = string.Empty;
            int taskType = -1;
            int taskStatus = -1;
            int pageSize = 10;
            int pageIndex = 1;
            int totalCount = 0;
            if (!string.IsNullOrEmpty(this.Request.Params["taskName"]))
            {
                taskName = this.Request.Params["taskName"];
            }
            if (!string.IsNullOrEmpty(this.Request.Params["taskType"]))
            {
                //taskType = formCollection["taskType"];
                int.TryParse(this.Request.Params["taskType"], out taskType);
            }
            if (!string.IsNullOrEmpty(this.Request.Params["taskStatus"]))
            {
                //taskStatus = formCollection["taskStatus"];
                int.TryParse(this.Request.Params["taskStatus"], out taskStatus);
            }
            if (!string.IsNullOrEmpty(formCollection["rows"]))
            {
                int.TryParse(formCollection["rows"], out pageSize);
            }
            if (!string.IsNullOrEmpty(formCollection["page"]))
            {
                int.TryParse(formCollection["page"], out pageIndex);
            }
            string order = Request.Params["order"];
            string sort = Request.Params["sort"];
            if (string.IsNullOrEmpty(sort))
            {
                sort = "CreateTime";
            }
            if (string.IsNullOrEmpty(order))
            {
                order = "asc";
            }
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ETLTaskBLL taskBll = new ETLTaskBLL(loginInfos);
            List<ETL_TaskInfo> list = taskBll.GetTaskList(taskName, taskType, taskStatus, sort, order, pageIndex, pageSize, out totalCount);

            foreach (ETL_TaskInfo taskModel in list)
            {
                var stime = Convert.ToDateTime(taskModel.TaskStartTime).ToString("HH:mm");
                var etime = Convert.ToDateTime(taskModel.TaskEndTime).ToString("HH:mm");
                taskModel.TaskStartTime = "执行一次：" + stime;
                if (taskModel.FrequencyType == 1)
                {
                    taskModel.TaskStartTime = string.Format("执行间隔：{0}分; [{1}-{2}]", taskModel.TaskEveryDayIntervalMinute, stime, etime);
                }
            }

            var jsonDict = new Dictionary<String, Object> { { "total", totalCount }, { "rows", list } };
            return Json(jsonDict);
        }

        public ActionResult GetTaskList_string(string dbName, FormCollection formCollection)
        {
            string taskName = string.Empty;
            string taskType = "";
            string taskStatus = "";
            int pageSize = 10;
            int pageIndex = 1;
            int totalCount = 0;
            if (!string.IsNullOrEmpty(formCollection["taskName"]))
            {
                taskName = formCollection["taskName"];
            }
            if (!string.IsNullOrEmpty(formCollection["taskType"]))
            {
                taskType = formCollection["taskType"];
                //int.TryParse(formCollection["taskType"], out taskType);
            }
            if (!string.IsNullOrEmpty(formCollection["taskStatus"]))
            {
                taskStatus = formCollection["taskStatus"];
                //int.TryParse(formCollection["taskStatus"], out taskStatus);
            }
            if (!string.IsNullOrEmpty(formCollection["rows"]))
            {
                int.TryParse(formCollection["rows"], out pageSize);
            }
            if (!string.IsNullOrEmpty(formCollection["page"]))
            {
                int.TryParse(formCollection["page"], out pageIndex);
            }
            string order = Request.Params["order"];
            string sort = Request.Params["sort"];
            if (string.IsNullOrEmpty(sort))
            {
                sort = "TaskName";
            }
            if (string.IsNullOrEmpty(order))
            {
                order = "asc";
            }
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ETLTaskBLL taskBll = new ETLTaskBLL(loginInfos);
            var list = taskBll.GetTaskList(taskName, taskType, taskStatus,
                sort, order
                , pageIndex, pageSize, out totalCount);

            var jsonDict = new Dictionary<String, Object> { { "total", totalCount }, { "rows", list } };
            return Json(jsonDict);
        }

        /// <summary>
        /// 删除任务
        /// </summary>
        /// <param name="taskID"></param>
        /// <param name="dbName"></param>
        /// <returns></returns>
        public ActionResult DeleteTask(string taskID, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            SysPublicBLL pbll = new SysPublicBLL(loginInfos);
            string DBType = pbll.GetDBInfo(dbName).DBType.ToString();
            ETLTaskBLL taskBll = new ETLTaskBLL(loginInfos);

            int result = taskBll.Delete2(taskID, DBType);

            if (result == 1)
            {
                new SysOperationLog(loginInfos).Log("作业任务管理", Request.UserHostAddress, OperationAction.删除, OperationStatus.成功,
                      "删除作业任务操作,操作成功,ID=" + taskID, Request.Cookies["MDM_UserName"] != null ? Request.Cookies["MDM_UserName"].Value : "");
                return Json(new
                   {
                       Success = true,
                       Message = "删除成功！"
                   });
            }
            else
            {
                new SysOperationLog(loginInfos).Log("作业任务管理", Request.UserHostAddress, OperationAction.删除, OperationStatus.失败,
                         "删除作业任务操作,操作失败,ID=" + taskID, Request.Cookies["MDM_UserName"] != null ? Request.Cookies["MDM_UserName"].Value : "");

                return Json(new
                   {
                       Success = false,
                       Message = "删除失败！"
                   });
            }

        }
        /// <summary>
        /// 立即执行任务
        /// </summary>
        /// <param name="taskID"></param>
        /// <param name="dbName"></param>
        /// <returns></returns>
        public ActionResult ExecuteTask(string taskID, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            SysPublicBLL pbll = new SysPublicBLL(loginInfos);
            string DBType = pbll.GetDBInfo(dbName).DBType.ToString();
            ETLTaskBLL etlTaskBLL = new ETLTaskBLL(loginInfos);
            if (etlTaskBLL.DoTask(taskID, DBType))
            {
                new SysOperationLog(loginInfos).Log("作业任务管理", Request.UserHostAddress, OperationAction.更新, OperationStatus.成功,
                    "立即执行任务操作,操作成功,ID=" + taskID, Request.Cookies["MDM_UserName"] != null ? Request.Cookies["MDM_UserName"].Value : "");
                return Json(new
                {
                    Success = true,
                    Message = "操作成功"
                });
            }
            else
            {
                new SysOperationLog(loginInfos).Log("作业任务管理", Request.UserHostAddress, OperationAction.更新, OperationStatus.失败,
                    "立即执行任务操作,操作失败,ID=" + taskID, Request.Cookies["MDM_UserName"] != null ? Request.Cookies["MDM_UserName"].Value : "");
                return Json(new
                    {
                        Success = false,
                        Message = "操作失败"
                    });
            }
        }

        /// <summary>
        /// 更新任务状态
        /// </summary>
        /// <param name="id">任务id</param>
        /// <param name="status"></param>
        public ActionResult UpdateTaskStatus(string taskID, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            SysPublicBLL pbll = new SysPublicBLL(loginInfos);
            string DBType = pbll.GetDBInfo(dbName).DBType.ToString();
            ETLTaskBLL taskBll = new ETLTaskBLL(loginInfos);
            var taskInfo = taskBll.GetTaskInfoById(taskID);
            if (taskInfo == null)
            {
                return Json(new
                {
                    Success = false,
                    Message = "任务不存在，请检查后重试。"
                });
            }
            if (taskInfo.TaskStatus == 1)
                taskInfo.TaskStatus = 0;
            else
            {
                taskInfo.TaskStatus = 1;
            }
            taskInfo.DBType = DBType;
            var result = taskBll.UpdateStatus(taskInfo);
            if (result == 1)
            {
                new SysOperationLog(loginInfos).Log("作业任务管理", Request.UserHostAddress, OperationAction.更新, OperationStatus.成功,
                    "更新任务状态操作,操作成功,ID=" + taskID + ",Status=" + taskInfo.TaskStatus, Request.Cookies["MDM_UserName"] != null ? Request.Cookies["MDM_UserName"].Value : "");
                return Json(new
                {
                    Success = true,
                    Message = "更新任务状态成功。"
                });
            }
            else
            {
                return Json(new
                {
                    Success = false,
                    Message = "更新任务状态失败。"
                });
            }
        }

        #endregion

        #region Edit

        public ActionResult Edit(string taskID, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ETLTaskBLL taskBll = new ETLTaskBLL(loginInfos);
            var taskInfo = taskBll.GetTaskInfoById(taskID);
            if (taskInfo.TaskID == null)
            {
                taskInfo = new ETL_TaskInfo()
                {
                    TaskIntervalDays = 1,
                    TaskEndDate = DateTime.Now.AddYears(100).ToString("yyyy-MM-dd"),
                    TaskStartDate = DateTime.Now.ToString("yyyy-MM-dd"),
                    RetryTimes = 2
                };
            }
            else
            {
                taskInfo.TaskStartTime = Convert.ToDateTime(taskInfo.TaskStartTime).ToShortTimeString();
                taskInfo.TaskEndTime = Convert.ToDateTime(taskInfo.TaskEndTime).ToShortTimeString();
            }
            return View(taskInfo);
        }
        /// <summary>
        /// 编辑任务信息
        /// </summary>
        /// <param name="taskID"></param>
        /// <param name="dbName"></param>
        /// <returns></returns>
        public ActionResult Update(FormCollection collection, string dbName)
        {
            #region 变量信息
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            EtlTargetSystemBLL targetSystemBLL = new EtlTargetSystemBLL(loginInfos);
            EtlSourceSystemBLL sourcesystemBll = new EtlSourceSystemBLL(loginInfos);
            ETLTaskBLL taskBll = new ETLTaskBLL(loginInfos);
            //var connList = GetDatabaseConnections(collection);
            var contacts = GetFormValues(Request.Params["UserList"], "UserList");
            var modelList = GetFormValues(Request.Params["ModelList"], "ModelList");
            var groupList = GetFormValues(Request.Params["GroupList"], "GroupList");
            string WeekDay = Request.Params["WeekDay"];
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            ETL_TaskInfo model = (ETL_TaskInfo)jsSerializer.Deserialize(Request.Params["postData"], typeof(ETL_TaskInfo));
            ETL_TaskInfo TaskPlanModel = (ETL_TaskInfo)jsSerializer.Deserialize(Request.Params["TaskPlan"], typeof(ETL_TaskInfo));

            #endregion

            #region 参数检查
            if (model.FrequencyType != 0)
            {
                if (model.TaskEveryDayIntervalMinute < 5)
                {
                    return Json(new
                   {
                       Success = false,
                       Message = "任务执行间隔时间不能为0！"
                   });
                }
                if (Convert.ToDateTime(model.TaskStartTime) >= Convert.ToDateTime(model.TaskEndTime))
                {
                    return Json(new
                   {
                       Success = false,
                       Message = "任务执行间隔结束时间必须大于开始时间！"
                   });
                }
            }
            if (string.IsNullOrEmpty(model.TaskName))
            {
                return Json(new
                {
                    //任务名称格式不正确，只能由数字、英文字母或者下划线组成!
                    Success = false,
                    Message = "任务名称不能为空！"
                });
            } 

            if (Convert.ToDateTime(model.TaskStartDate) >= Convert.ToDateTime(model.TaskEndDate))
            {
                return Json(new
               {
                   Success = false,
                   Message = "失效日期必须大于生效日期！"
               });
            }
            #endregion

            #region 更新数据
            if (string.IsNullOrEmpty(model.TaskID))
            {
                model.TaskID = Guid.NewGuid().ToString();
            }
            // 更新任务数据
            switch (model.TaskPlanType)
            {
                case 1:
                    model.TaskIntervalDays = TaskPlanModel.TaskIntervalDays;
                    break;
                case 2:
                    model.TaskIntervalDays = int.Parse(TaskPlanModel.TaskIntervalWeeks);
                    break;
                case 3:
                    model.TaskIntervalDays = int.Parse(TaskPlanModel.TaskIntervalMonth);
                    model.WeekDay = TaskPlanModel.DayForMonth;
                    break;
            }
            if (!string.IsNullOrEmpty(WeekDay))//转换任务计划类型为“周”时第几周
            {
                double freq_interval = 0;
                foreach (string w in WeekDay.Split(','))
                {
                    double wk = Math.Pow(2, double.Parse(w));//转换周数到freq_interval 如周3转为8
                    freq_interval = freq_interval + wk;
                }
                model.WeekDay = freq_interval.ToString();
            }
            model.DBName = dbName;
            var taskResult = taskBll.SaveTask(model);
            if (taskResult == 1)
            {
                #region 更新执行时间
                TaskPlanModel.TaskPlanType = model.TaskPlanType;
                TaskPlanModel.TaskGuid = model.TaskID;
                TaskPlanModel.TaskEveryDayIntervalMinute = model.TaskEveryDayIntervalMinute;
                TaskPlanModel.WeekDay = WeekDay;
                if (TaskPlanModel.PlanType == "2")
                    TaskPlanModel.TaskIntervalMonth = TaskPlanModel.TaskIntervalMonth2;
                taskBll.SaveTaskPlan(TaskPlanModel);
                #endregion

                #region 更新明细

                var detailsList = new List<ETL_Task_Details>();
                int index = 0;
                foreach (var modelID in modelList)
                {
                    detailsList.Add(new ETL_Task_Details()
                    {
                        GUID = Guid.NewGuid().ToString(),
                        TaskID = model.TaskID,
                        JobStepID = modelID,
                        JobStepOrderID = index++,
                        StepType = "T"
                    });
                }

                foreach (var groupID in groupList)
                {
                    detailsList.Add(new ETL_Task_Details()
                    {
                        GUID = Guid.NewGuid().ToString(),
                        TaskID = model.TaskID,
                        JobStepID = groupID,
                        JobStepOrderID = index++,
                        StepType = "L"
                    });
                }
                taskBll.SaveTaskDetails(model.TaskID, detailsList);
                #endregion

                #region 联系人信息
                SqlParameter[] cmdParms = new SqlParameter[]
                {
                    new SqlParameter("@SysID",model.TaskID)
                };
                var oldContactsList = sourcesystemBll.GetEtlSourceUserList(cmdParms);
                // 先处理已经存在的
                foreach (var oldContactInfo in oldContactsList)
                {
                    if (!contacts.Contains(oldContactInfo.Guid))// 删除联系人
                    {
                        sourcesystemBll.DeleteContact(oldContactInfo.Guid, model.TaskID);
                    }
                }
                foreach (string contact in contacts)
                {
                    string uid = contact;
                    bool isHas = false;
                    if (!string.IsNullOrEmpty(uid))
                    {
                        foreach (var oldContactInfo in oldContactsList)
                        {
                            if (oldContactInfo.Guid.Equals(uid, StringComparison.CurrentCultureIgnoreCase))
                            {
                                isHas = true;
                                break;
                            }
                        }
                        if (isHas == false)
                        {
                            // 不存在，增加新的联系人
                            EtlContactInfo contactInfo = new EtlContactInfo()
                            {
                                GUID = Guid.NewGuid().ToString(),
                                UserID = uid,
                                SysID = model.TaskID,
                                SysType = 1
                            };
                            sourcesystemBll.AddContact(contactInfo);
                        }
                    }
                }
                #endregion
            }

            #endregion

            #region 输出结果
            if (taskResult == 1)
            {
                new SysOperationLog(loginInfos).Log("作业任务管理", Request.UserHostAddress, OperationAction.更新, OperationStatus.成功,
                        "更新作业任务操作,操作成功,ID=" + model.TaskID, Request.Cookies["MDM_UserName"] != null ? Request.Cookies["MDM_UserName"].Value : "");

                return Json(new
                {
                    Success = true,
                    Message = "保存成功"
                });
            }
            else if (taskResult == 0)
            {
                return Json(new
                {
                    Success = false,
                    Message = "保存失败"
                });
            }
            else if (taskResult == 2)
            {
                return Json(new
                {
                    Success = false,
                    Message = "保存失败，存在相同的任务名称"
                });
            }
            else
            {
                return Json(new
                {
                    Success = false,
                    Message = "保存失败"
                });
            }
            #endregion
        }

        public JsonResult GetTargetUserList(string taskID, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            EtlSourceSystemBLL bll = new EtlSourceSystemBLL(loginInfos);
            taskID = string.IsNullOrEmpty(taskID) ? "" : taskID;
            IList<SysUserInfo> list = bll.GetEtlSourceUserList(new IDataParameter[] { new SqlParameter("@SysID", taskID) });
            Dictionary<String, Object> jsonDict = new Dictionary<String, Object>();
            jsonDict.Add("total", list.Count);
            jsonDict.Add("rows", list);
            return Json(jsonDict);
        }

        public JsonResult GetTaskDetailsList(string taskID, string type, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            SysPublicBLL pBll = new SysPublicBLL(loginInfos);
            DBDeploy dbInfo = pBll.GetDBInfo(dbName);
            ETLTaskBLL taskBll = new ETLTaskBLL(loginInfos);
            ModelConfigBLL modelBll = new ModelConfigBLL(loginInfos);
            SysViewGroupBLL groupBll = new SysViewGroupBLL(loginInfos);
            List<TaskDetailModel> modelList = taskBll.GetTaskDetailsByTaskID(taskID, type, dbInfo.DBType);

            var jsonDict = new Dictionary<String, Object>();
            jsonDict.Add("total", modelList.Count);
            jsonDict.Add("rows", modelList);
            return Json(jsonDict);
        }

        #endregion

        #region 取任务执行计划表

        public ActionResult TaskStatus(string dbName)
        {
            return View();
        }

        /// <summary>
        /// 取任务执行计划表
        /// </summary>
        /// <returns></returns>
        public string GetTaskRunStatus(string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ETLTaskBLL etlTaskBLL = new ETLTaskBLL(loginInfos);
            DataTable dt = etlTaskBLL.TaskRunStatus("", 1, 0);//取任务执行计划表
            DataTable dtClone = dt.Clone();
            for (int j = 4; j < dt.Columns.Count; j++)
            {
                dtClone.Columns[j].DataType = typeof(string);
            }
            foreach (DataRow dr in dt.Rows)
            {
                DataRow drClone = dtClone.Rows.Add();
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    if (j < 4)
                        drClone[j] = dr[j].ToString();
                    else
                    {
                        switch (dr[j].ToString())
                        {
                            case "0":
                                drClone[j] = "<div class='c0 cw'>×</div>";
                                break;
                            default:
                                drClone[j] = "<div class='c" + dr[j].ToString() + " cw'>√</div>";
                                break;
                        }
                    }
                }
            }
            Dictionary<string, string> columnNameDics = new Dictionary<string, string>();
            columnNameDics.Add("TaskName".ToUpper(), "任务名称");
            columnNameDics.Add("TaskStatus".ToUpper(), "任务状态");
            columnNameDics.Add("TaskIntervalDays".ToUpper(), "按日间隔");
            columnNameDics.Add("TaskEveryDayIntervalMinute".ToUpper(), "分钟间隔");
            var strDT = this.DataTableToString(dt, columnNameDics);
            return strDT;
        }

        private string DataTableToString(DataTable dt, Dictionary<string, string> columnNameDics)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("");

            if (dt.Columns.Count > 0)
            {
                sb.AppendLine("<table id=\"tbSoutceTableData\" class=\"pagTable\" width='100%' style=\"border-collapse: collapse;\" cellspacing=\"0\" cellpadding=\"0\">");
                sb.AppendLine(" <thead>");
                sb.AppendLine(" <tr class=\"Freezing\">");
                string width = (100 / dt.Columns.Count).ToString() + "%";
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    string textalign = "";
                    if (dt.Columns[i].DataType.Equals(typeof(int))
                        || dt.Columns[i].DataType.Equals(typeof(float))
                        || dt.Columns[i].DataType.Equals(typeof(DateTime)))
                    {
                        textalign = "right";
                    }
                    else
                    {
                        textalign = "left";
                    }
                    string columnName = dt.Columns[i].ColumnName;
                    string columnCaption = dt.Columns[i].ColumnName;
                    if (columnNameDics != null && columnNameDics.ContainsKey(columnName.ToUpper()))
                    {
                        if (!string.IsNullOrEmpty(columnNameDics[columnName.ToUpper()]))
                        {
                            columnCaption = columnNameDics[columnName.ToUpper()];
                        }
                    }
                    if (columnName.Equals("TaskName"))
                    {
                        width = "100px";
                    }
                    else if (columnName.Equals("TaskStatus"))
                    {
                        width = "100px";
                    }
                    else if (columnName.Equals("TaskIntervalDays"))
                    {
                        width = "100px";
                    }
                    else if (columnName.Equals("TaskEveryDayIntervalMinute"))
                    {
                        width = "100px";
                    }
                    else
                    {
                        width = "40px";
                    }
                    if (i < 4)
                    {
                        sb.AppendLine(string.Format("     <td class=\"pagTablehd\" style=\"width: {0}; text-align: {1};\" >"
                            , width, textalign, "auto"));
                    }
                    else
                    {
                        sb.AppendLine(string.Format("     <td class=\"pagTablehd\" style=\"width: {0}; text-align: {1};\" >"
                            , width, textalign, "auto"));
                    }

                    sb.AppendLine(string.Format("         <nobr>{0}</nobr>", columnCaption));
                    sb.AppendLine("     </td>");
                }
                sb.AppendLine(" </tr>");
                sb.AppendLine(" </thead>");
                int rowNumber = 0;
                sb.AppendLine("<tbody>");
                foreach (DataRow rowItem in dt.Rows)
                {
                    if (rowNumber++ % 2 == 0)
                    {
                        sb.AppendLine(" <tr style=\"background: #fff;\">");
                    }
                    else
                    {
                        sb.AppendLine(" <tr class=\"tr_c2\">");
                    }
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        string textalign = "";
                        if (dt.Columns[i].DataType.Equals(typeof(int))
                            || dt.Columns[i].DataType.Equals(typeof(float))
                            || dt.Columns[i].DataType.Equals(typeof(DateTime)))
                        {
                            textalign = "right";
                        }
                        else
                        {
                            textalign = "left";
                        }

                        var value = rowItem[i] == null || string.IsNullOrEmpty(rowItem[i].ToString()) ? "&nbsp;" : rowItem[i].ToString();
                        var title = value.Equals("&nbsp;") ? "" : string.Format("内容：{0}", value, value.Length);
                        if (i < 4)
                        {
                            sb.AppendLine(string.Format("     <td class=\"FreezingCol\" style=\"text-align: {0};\" title=\"{1}\">", textalign, title));
                        }
                        else
                        {
                            sb.AppendLine(string.Format("     <td style=\"text-align: {0};\" title=\"{1}\">", textalign, title));
                        }
                        //if (dt.Columns[i].DataType.Equals(typeof(DateTime)))
                        {
                            sb.AppendLine("     <nobr>");
                        }
                        sb.AppendLine(string.Format("         {0}", value));
                        //if (dt.Columns[i].DataType.Equals(typeof(DateTime)))
                        {
                            sb.AppendLine("     </nobr>");
                        }
                        sb.AppendLine("     </td>");
                    }
                    sb.AppendLine(" </tr>");
                }
                sb.AppendLine("</tbody>");
                sb.AppendLine("</table>");
            }
            return sb.ToString();
        }
        #endregion

        #region TaskLog

        public ActionResult TaskLog(string dbName)
        {
            return View();
        }
        /// <summary>
        /// 取任务日志
        /// </summary> 
        /// <returns></returns>
        public ActionResult GetTaskLog(string dbName, string taskID, int rows, int page)
        {
            string taskType = Request.Params["taskType"];
            string taskStatus = Request.Params["taskStatus"];
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            SysPublicBLL pbll = new SysPublicBLL(loginInfos);
            string DBType = pbll.GetDBInfo(dbName).DBType.ToString();
            ETLTaskBLL etlTaskBLL = new ETLTaskBLL(loginInfos);
            List<ETL_Task_Details_HistoryLog> list = etlTaskBLL.GetTaskLogByTaskID(taskID, taskType, taskStatus, rows, page, DBType);//取任务日志列表
            foreach (ETL_Task_Details_HistoryLog model in list)
            {
                if (!string.IsNullOrEmpty(model.StartTime))
                    model.StartTime = Convert.ToDateTime(model.StartTime).ToString("yyyy-MM-dd HH:mm:ss");
                if (!string.IsNullOrEmpty(model.EndTime))
                    model.EndTime = Convert.ToDateTime(model.EndTime).ToString("yyyy-MM-dd HH:mm:ss");
                if (!string.IsNullOrEmpty(model.BatchTime))
                    model.BatchTime = Convert.ToDateTime(model.BatchTime).ToString("yyyy-MM-dd HH:mm:ss");
                model.RunDuration = model.RunDuration + "秒";
            }
            int count = 0;
            if (list.Count > 0)
                count = list[0].Count;
            Dictionary<String, Object> jsonDict = new Dictionary<String, Object>();
            jsonDict.Add("total", count);
            jsonDict.Add("rows", list);
            return Json(jsonDict);
        }
        /// <summary>
        /// 取所有实例下任务日志
        /// </summary> 
        /// <returns></returns>
        public ActionResult GetAllTask(string dbName, int rows, int page)
        {
            string taskName = Request.Params["taskName"];
            string taskType = Request.Params["taskType"];
            string taskStatus = Request.Params["taskStatus"];
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ETLTaskBLL etlTaskBLL = new ETLTaskBLL(loginInfos);
            int enable = etlTaskBLL.CheckDBJob(dbName);
            Dictionary<String, Object> jsonDict = new Dictionary<String, Object>();
            if (enable == 1)
            {
                List<ETL_Task_Details_HistoryLog> list = etlTaskBLL.GetAllTaskLog(taskName, taskType, taskStatus, rows, page);//取任务日志列表
                foreach (ETL_Task_Details_HistoryLog model in list)
                {
                    if (!string.IsNullOrEmpty(model.StartTime))
                        model.StartTime = Convert.ToDateTime(model.StartTime).ToString("yyyy-MM-dd HH:mm:ss");
                    if (!string.IsNullOrEmpty(model.EndTime))
                        model.EndTime = Convert.ToDateTime(model.EndTime).ToString("yyyy-MM-dd HH:mm:ss");
                    if (!string.IsNullOrEmpty(model.BatchTime))
                        model.BatchTime = Convert.ToDateTime(model.BatchTime).ToString("yyyy-MM-dd HH:mm:ss");
                    model.RunDuration = model.RunDuration + "秒";
                }
                int count = 0;
                if (list.Count > 0)
                    count = list[0].Count;
                jsonDict.Add("total", count);
                jsonDict.Add("rows", list);
                return Json(jsonDict);
            }
            else if (enable == 0)
            {
                jsonDict.Add("exMsg", "该实例下作业状态未启用，请检查作业状态。");
                return Json(jsonDict);
            }
            else
            {
                jsonDict.Add("exMsg", "该实例下没有部署的作业，请检查部署状态。");
                return Json(jsonDict);

            }
        }
        public ActionResult GetTaskLogItem(string dbName, string id)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ETLTaskBLL etlTaskBLL = new ETLTaskBLL(loginInfos);
            List<ETL_Task_Details_HistoryLog> list = etlTaskBLL.GetTaskLogItem(id);//取任务日志信息
            ETL_Task_Details_HistoryLog model = new ETL_Task_Details_HistoryLog();
            if (list.Count > 0)
                model = list[0];
            return Json(model);
        }

        #endregion

        #region 公共单元

        private List<string> GetFormValues(string values, string name)
        {
            List<string> list = new List<string>();
            if (string.IsNullOrEmpty(values))
            {
                return list;
            }
            list = values.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            return list;
        }

        #endregion
    }
}
